package org.rpc.protocol;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class HttpServer {
    public void start(String hostName, Integer port, String contextPath) throws LifecycleException {
        System.out.println("server start......");
        //创建容器
        Tomcat tomcat = new Tomcat();
        //获取服务
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        //创建连接
        Connector connector = new Connector();
        //设置连接端口
        connector.setPort(port);
        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostName);
        //创建host
        Host host = new StandardHost();
        host.setName(hostName);
        if (contextPath == null) {
            contextPath = "/";
        }
        //创建上下文
        Context context = new StandardContext();
        context.setPath(contextPath);
        //监听上下文
        context.addLifecycleListener(new Tomcat.FixContextListener());
        host.addChild(context);
        engine.addChild(host);
        service.setContainer(engine);
        service.addConnector(connector);
        //创建servlet
        tomcat.addServlet(contextPath, "dispatchServlet", new DispatchServlet());
        // servletUrl映射,任意请求都交由dispatchServlet处理
        context.addServletMappingDecoded("/*", "dispatchServlet");
        //启动tomcat
        tomcat.start();
        // 异步进行接收请求
        tomcat.getServer().await();
    }
}
